package com.edu.gdkm.servlet.ticket;

import com.edu.gdkm.dao.dypDao;
import com.edu.gdkm.db.table.ticket;
import com.edu.gdkm.util.cookiesUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/ticketServlet")
public class ticketServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        cookiesUtil util = new cookiesUtil();
        List<ticket> tickets = new ArrayList<>();

        Cookie c = util.findCookie(req.getCookies(), "dyp_user");
        String[] user = util.splitCookies(c);
        try {
            // 打开数据库
            dypDao dao = new dypDao();
            // 查询 => 该用户的所有的电影票号
            List<String> kids = new ArrayList<>();
            ResultSet kid = dao.select("kid", "filmegener", "cid="+user[1]);   // 查询所有票号
            while (kid.next())
                kids.add(   // 存储
                        kid.getString(1));  // 获取首列数据
            kid.close();                                                               // 关闭
            // 遍历 => 存储电影票信息至列表
            for (String k: kids) {
                // 电影票数据封装
                tickets.add(    // 添加列表
                        dao.getTicket(  // 封装
                                dao.selectStors("sel_filmegener", k)));  // 调用存储过程
            }
            dao.close(); // 关闭
        } catch (SQLException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        // 会话域存储
        req.getSession().setAttribute("tickets", tickets);
        // 跳转
        req.getRequestDispatcher("orders.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
